package com.demo.serviceimpl;

import com.demo.bean.User;
import com.demo.service.RedisService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 李天航
 * 操作redis的服务
 */
@Service
public class RedisServiceImpl implements RedisService {
    @Resource
    RedisTemplate<String, Object> redisTemplate;
    /**
     * 前缀，配合userAccount
     */
    private final String sessionIdSuffix="-session";
    /**
     * 后缀，配合sessionId
     */
    private final String sessionIdPrefix="session-";

    @Override
    public String getUserIp(String userAccount) {
        return (String) redisTemplate.boundValueOps(userAccount+"ip").get();
    }

    @Override
    public void setUserIp(String userAccount, String ipAddress) {
        System.out.println(getUserIp(userAccount));
        redisTemplate.boundValueOps(userAccount+"ip").set(ipAddress);
        System.out.println(getUserIp(userAccount));
    }

    @Override
    public void setUserSessionId(String userAccount, String sessionId) {
        String rawSessionId= (String) redisTemplate.opsForValue().get(userAccount+sessionIdSuffix);
        if(rawSessionId!=null){
            redisTemplate.delete(sessionIdPrefix+rawSessionId);
        }
        Double ranDom=Math.random()*10;
        redisTemplate.opsForValue().set(userAccount+sessionIdSuffix,sessionId,10+ranDom.longValue(), TimeUnit.MINUTES);
    }

    /**
     * 获取账号被哪个session所使用
     *
     * @param userAccount 用户账号
     * @return sessionId
     */
    @Override
    public String getSessionIdByUserAccount(String userAccount) {
        return (String) redisTemplate.opsForValue().get(userAccount+sessionIdSuffix);
    }

    /**
     * 分布式session，存储数据
     *
     * @param sessionId session编号
     * @param key       key值
     * @param data      数据
     */
    @Override
    public void setSessionData(String sessionId, String key, Object data) {
        if(data==null){
            redisTemplate.opsForHash().delete(sessionId,key);
        }
        else {

            redisTemplate.opsForHash().put(sessionIdPrefix + sessionId, key, data);
        }
    }

    /**
     * 获取相关数据
     *  @param sessionId 编号
     * @param key       键值
     * @return
     */
    @Override
    public Object getSessionData(String sessionId, String key) {
        return redisTemplate.opsForHash().get(sessionIdPrefix + sessionId, key);
    }

    /**
     * 重置过期时间
     *
     * @param sessionId 键值
     */
    @Override
    public void resetKeyTime(String sessionId) {
        User user= (User) getSessionData(sessionId,"user");
        if(user==null) {
            return;
        }
        redisTemplate.expire(sessionIdPrefix+sessionId,10,TimeUnit.MINUTES);
        redisTemplate.expire(user.getUserAccount()+sessionIdSuffix,10,TimeUnit.MINUTES);
    }

}
